import Mongo, { ObjectId } from "mongodb";

export const host = '115.28.106.143'

export const MONGO_URL = `mongodb://${host}:27017/`;

export const MONGOOSE_URL = `mongodb://${host}:27017/test`;

class GetMongoConnect {
  client: Promise<Mongo.MongoClient>;
  constructor() {
    this.connect();
  }
  // 连接数据库
  async connect(): Promise<any> {
    this.client = (async (): Promise<Mongo.MongoClient> => {
      const result = await Mongo.MongoClient.connect(MONGO_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true, //这个即是报的警告
      });
      return result;
    })();
  }
  // 查找
  async find(
    db: string,
    col: string,
    query: { [key: string]: any }
  ): Promise<any> {
    return await (await this.client)
      .db(db)
      .collection(col)
      .find(query)
      .toArray();
  }
  // 新增
  async add(
    db: string,
    col: string,
    query: { [key: string]: any }
  ): Promise<any> {
    return await (
      await (await this.client).db(db).collection(col).insertOne(query)
    ).result;
  }
  // 删除
  async delete(
    db: string,
    col: string,
    query: { [key: string]: any }
  ): Promise<any> {
    return await (
      await (await this.client).db(db).collection(col).deleteOne(query)
    ).result;
  }
  // 修改
  async update(
    db: string,
    col: string,
    query: { [key: string]: any },
    updateTarget: { [key: string]: any }
  ): Promise<any> {
    return await (await this.client)
      .db(db)
      .collection(col)
      .updateOne(query, { $set: updateTarget });
  }
  // 关闭数据库
  async close(): Promise<void> {
    (await this.client).close();
  }
}

const getObjectId = (_id: string | string[]): Mongo.ObjectID => {
  return new ObjectId(typeof _id === "string" ? _id : "");
};

const mysqlconfig = {
  host: '127.0.0.1', //服务器ip
  user: "root", //mysql用户名
  password: "123456", //mysql密码
  database: "user", //数据库名称
  port: 3306, //mysql端口号
};

export { GetMongoConnect, getObjectId, mysqlconfig };
